import { constantRoutes } from '@/router' // asyncRoutes,
import { getBuild } from '@/api/system/menu'// getTree,
import Layout from '@/layout/index'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  buttons: [],
  roleType: ''
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  SET_ROLE_TYPE: (state, roleType) => {
    state.roleType = roleType
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 获取菜单
      getBuild().then(result => {
        let res = filterAsyncRouter(result.data.list)
        res = res.map(item => {
          //  处理只有一个子菜单情况
          if (item.children && item.children.length === 1) {
            item.redirect = item.path + '/' + item.children[0].path
            item.children[0].meta.title = item.meta.title
            item.meta = null
            item.alwaysShow = null
          }
          return item
        })
        // console.log(res)
        // let accessedRoutes
        // if (roles.includes('admin')) {
        //   accessedRoutes = asyncRoutes || []
        // } else {
        //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        // }
        const buttonAuthList = result.data.buttons
        const roleType = result.data.roleType
        commit('SET_ROUTES', res)
        commit('SET_BUTTONS', buttonAuthList)
        commit('SET_ROLE_TYPE', roleType)
        resolve(res)
      })
    })
  }
}

export const filterAsyncRouter = (routers) => { // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter(router => {
    if (router.component) {
      if (router.component === 'Layout') { // Layout组件特殊处理
        router.component = Layout
      } else {
        const component = router.component
        router.component = loadView(component)
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }
    return true
  })
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
